<template>
    <div class="pay-order">
        <titleBar title="填写订单" />
        <div class="pay-address">
            <div class="select flex flex-space-x" v-on:click="goAddAddress()" v-if="!addressInfo">
                <div>
                    <i class="iconfont i-address icon-dizhi"></i>
                    <span class="text">选择联系方式及地点</span>
                </div>
                <i class="iconfont i-go icon-iconfonticonfonti2copycopy"></i>
            </div>
            <div class="flex address-info-box flex-space-x" v-on:click="goAddAddress()" v-if="addressInfo">
                <div class="pay-info">
                    <div class="flex info-one">
                        <p class="real-name">{{addressInfo.userName}}</p>
                        <p class="real-phone">{{addressInfo.phone}}</p>
                    </div>
                    <p class="address-text">{{addressInfo.address}} {{addressInfo.addressInfo}}</p>
                </div>
                <i class="iconfont i-go icon-iconfonticonfonti2copycopy"></i>
            </div>
        </div>
        <div class="flex item flex-center-y" v-on:click="isOpTimes = true">
            <div class="name">预约日期</div>
            <div class="inner">
                <span class="data-name" v-if="payOrderConventionDate.length > 0">{{
                    payOrderConventionDate
                    .map(e => e)
                    .sort((a, b) => (+new Date(a)) - (+new Date(b)))
                    /*.map(v => {
                        let e = v.split('/')
                        return `${e[1]}${e[2]}`
                    })*/
                    .join('、')
                }}</span>
                <span v-else class="tip">请选择预约日期</span>
            </div>
            <i class="iconfont i-go icon-iconfonticonfonti2copycopy"></i>                
        </div>
        <div class="flex item" v-on:click="openUpdoorDate = true">
            <div class="name">上门时间</div>
            <div class="inner">
                <span class="tip" v-if="!payOrderUpDoorDateCelectActive">请选择</span>
                <span v-else class="data-name">{{payOrderUpDoorDateCelectActive}}</span>
            </div>
            <i class="iconfont i-go icon-iconfonticonfonti2copycopy"></i>                
        </div>
        <div class="flex item" v-on:click="$router.push('project_name')">
            <div class="name">项目名称</div>
            <div class="inner">
                <span class="tip" v-if="!payOrderProjectName">请输入项目名称</span>
                <span v-else class="data-name">{{payOrderProjectName}}</span>
            </div>
            <i class="iconfont i-go icon-iconfonticonfonti2copycopy"></i>                
        </div>
        <div class="flex item" v-on:click="openDemand = true">
            <div class="name">需求效果</div>
            <div class="inner">
                <span class="tip" v-if="!payOrderDemandActive">请选择</span>
                <span v-else class="data-name">{{payOrderDemandActive}}</span>
            </div>
            <i class="iconfont i-go icon-iconfonticonfonti2copycopy"></i>                
        </div>
        <div class="flex item" v-on:click="isPayWay = true">
            <div class="name">支付方式</div>
            <div class="inner">
                <span class="tip" v-if="!payWay">请选择</span>
                <span v-else class="data-name">{{payWay}}</span>
            </div>
            <i class="iconfont i-go icon-iconfonticonfonti2copycopy"></i>                
        </div>
        <div class="button-box">
            <div class="button" v-on:click="success">总计 {{totalPrice}}元 支付</div>
        </div>
        <div class="upDoor-popup" v-if="openUpdoorDate">
            <div class="mask"></div>
            <div class="inner">
                <div class="flex handleColum flex-space-x">
                    <span class="close" v-on:click="openUpdoorDate = false">取消</span>
                    <span class="done" v-on:click="updoorDateDone">完成</span>
                </div>
                <van-picker :default-index="payOrderUpDoordateCelectIndex" :columns="dateCelectColumns" @change="upDoordateCelectOnChange" />
            </div>
        </div>
        <!-- 需求效果 -->
        <div class="upDoor-popup" v-if="openDemand">
            <div class="mask"></div>
            <div class="inner">
                <div class="flex handleColum flex-space-x">
                    <span class="close" v-on:click="openDemand = false">取消</span>
                    <span class="done" v-on:click="demandDone">完成</span>
                </div>
                <van-picker :default-index="payOrderDemandIndex" :columns="demandList" @change="demandChange" />
            </div>
        </div>
        <div v-if="isPayWay" class="upDoor-popup pay-way-box">
            <div class="mask"></div>
            <div class="inner">
                <div class="flex flex-space-x handle-head">
                    <div></div>
                    <div class="title-name">请选择支付方式</div>
                    <div class="close-block" v-on:click="isPayWay = false">
                        <i class="iconfont icon-guanbi1"></i>
                    </div>
                </div>
                <div class="pay-list">
                    <div
                     class="pay-item flex flex-center-y flex-space-x" 
                     v-for="(item, index) in payWayList" 
                     :key="index"
                     v-on:click="switchPayWay(index)">
                        <div class="flex flex-center-y">
                            <i v-if="item.icon" class="pay-way-wconfont iconfont" :class="[item.icon]" :style="item.styles"></i>
                            <img class="pay-way-wconfont" v-if="item.img" :src="item.img" />
                            <span>{{item.name}}</span>
                        </div>
                        <i v-if="payOrderPayWayActiveIndex === index" class="select-block iconfont icon-dui"></i>
                        <i v-else></i>
                    </div>
                    <div class="pay-item flex flex-center-y flex-space-x" :key="`_${index}`" v-on:click="addBank">
                        <div class="flex flex-center-y">
                            <img class="pay-way-wconfont" src="@/assets/img/performance/homePage/bank.png" />
                            <span>银行卡账号</span>
                        </div>
                        <div class="add" v-on:click="addBank">
                            <span>添加</span>
                            <i class="iconfont icon-iconfonticonfonti2copycopy"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="calendar-box">
            <calendar 
                :nowD="new Date()" 
                :close="calendarClose" 
                :open="isOpTimes" 
                :cb="onFilterTime" 
                :fullDate="payOrderSelectDateFullDateArr"
                :selecteds="payOrderConventionDate"
                :price="realPrice"
            />
        </div>
    </div>
</template>
<script>
import titleBar from '@/components/title_bar/index.vue'
import {mapState, mapMutations} from 'vuex'
import {dafaultDateCelectColumns, dafaultDemandList, defaultPayWayList} from './constant.js'
import Calendar from '@/components/performance/vue-calendar/index.vue'
import success from './pay.js'
import {getuserUid} from '@/utils/auth.js'
export default {
    components: {
        titleBar,
        Calendar
    },
    computed: {
        ...mapState([
            'payOrderProjectName',
            'payOrderUpDoordateCelectIndex',
            'payOrderUpDoorDateCelectActive',
            'payOrderConventionDate',
            'payOrderDemandIndex',
            'payOrderDemandActive',
            'payOrderDemandUid',
            'payOrderPayWayActiveIndex',
            'payOrderSelectDateFullDateArr',
        ]),
        totalPrice(v){
            console.log('this.payOrderDemandActive')
            console.log(this.payOrderDemandActive)
            let isAsyncModel = false
            try {
                // 全景图1.5倍。和某新讨论过了
                isAsyncModel = this.payOrderDemandActive.includes('360全景图')   
            } catch (error) {
                console.log(error)
            }
            let multiple = isAsyncModel ? 1.5 : 1
            return (this.oPrice * this.payOrderConventionDate.length * multiple).toFixed('2')
        },
        realPrice(v){
            let isAsyncModel = false
            try {
                // 全景图1.5倍。和某新讨论过了
                isAsyncModel = this.payOrderDemandActive.includes('360全景图')   
            } catch (error) {
                console.log(error)
            }
            let multiple = isAsyncModel ? 1.5 : 1
            return this.oPrice * multiple
        },
        payWay(v){
            return this.payWayList[this.payOrderPayWayActiveIndex]?.name
        },
    },
    data(){
        return {
            oPrice: 0,
            // totalPrice: '0.00',
            // 上门时间
            dateCelectColumns: [],
            openUpdoorDate: false,
            upDoordateCelect: void 0,
            // 预约日期
            isOpTimes: false,
            // 需求效果
            demandList: [],
            openDemand: false,
            demandCelect: void 0,
            // 支付
            isPayWay: false,
            // payWay: '',
            payWayList: defaultPayWayList,
            // 日历
            selectDateSelectedArr: [],
            selectDateFullDateArr: [],
            // 地址
            addressInfo: void 0,
            // 地址选择后的UID
            addressuid: 0,
            // 拉取的效果图列表
            /**
             * name: 
             * uid
             * id
             */
            orightSkill: [],
            // 表现师UID
            businessUserUid: void 0,
            // 支付中
            payRun: false,
            // 支付的订单号
            outTradeNo: 0,
            // 上门时间列表
            updoorDateList: []
        }
    },
    mounted(){
        console.log(this.$store.state)
    },
    async created(){
        this.$dialog.close()
        let errorHandle = () => {
            console.log('参数错误')
            this.$toast('参数异常')
            this.$router.go(-1)
        }
        let price = this.$route.query?.price
        let addressuid = this.$route.query?.addressuid
        let selectDate =  this.payOrderConventionDate
        let userUid = this.$route.query?.userUid
        if(!price){
            errorHandle()
            return
        }
        if(!userUid){
            errorHandle()
            return
        }
        if(selectDate.length === 0){
            console.log('预约日期异常')
            errorHandle()
            return
        }
        this.oPrice = +price
        this.businessUserUid = userUid
        console.log(price)
        console.log(selectDate)
        if(addressuid){
            let addressResponse = await HTTP('app/userAddress/addressDetailByUid', {
                addressUid: addressuid,
            })
            try {
                if(addressResponse.code !== 200){
                    this.$toast( addressResponse.msg|| '服务器异常')
                    return
                }
                console.log('---addressResponse--')
                console.log(addressResponse.data)
                this.addressInfo = addressResponse.data
                this.addressuid = addressuid
            } catch (error) {
                this.$toast('数据开小差了')
                console.log(error)
            }
        }
        this.setSkillList()
        this.bankList()
        this.getupdoorDate((list) => {            
            console.log('---获取的上门时间---')
            console.log(list)
            // 设置上门时间列表
            this.dateCelectColumns = dafaultDateCelectColumns(list, selectDate)
            this.updoorDateList = list.map(e => e)
        })
    },
    methods: {
        getHMD(timen){
            var time = new Date(timen)
            var year = time.getFullYear(time)
            var month = time.getMonth(time) + 1
            var date = time.getDate(time)
            return [year, month, date].join('-')
        },
        async getupdoorDate(cb){
            const Toast =TESTVUE.$toast.loading({
                duration: 0,       // 持续展示 toast
                // forbidClick: true, // 禁用背景点击
                loadingType: 'spinner',
                mask: true,
                message: ''
            })
            let params = {
                bUserUid: this.businessUserUid,
                serviceDate: this.getHMD(Math.min.apply(null,
                    this.payOrderConventionDate
                    // .map(e => e)
                    // .sort((a, b) => (+new Date(a)) - (+new Date(b)))
                    .map(e => +new Date(e.replace(/-/g, '/')))
                ))
            }
            let response = await HTTP('app/buser/getBUserServiceTimes', params)
            if(response.code !== 200){
                this.$toast(response.msg)
                return
            }
            cb(response.data.map(e => e.preordainTime))
            Toast.clear()
        },
        async bankList(){
            let params = {
                userUid: getuserUid(),
            }
            let bankResponse
            try {
                bankResponse = await HTTP('app/user/getUserBankCards', params)
                if(bankResponse.code !== 200){
                    this.$toast(bankResponse.msg)
                    return
                }
                console.log('银行卡列表')
                console.log(bankResponse.data)
                this.payWayList = [
                    ...defaultPayWayList,
                    ...bankResponse.data.map(e => {
                        return {
                            ...e,
                            name: `${e.bankName ? e.bankName : '银行卡'}(${e.bankCardNumber.substr(e.bankCardNumber.length - 4)})`,
                            img: require('@/assets/img/performance/homePage/bank.png')
                        }
                    })
                ]
                // this.orightBankList = bankResponse.data
            } catch (error) {
                this.$toast('数据开小差了')
                console.log(error)
            }
        },
        async setSkillList(){ 
            // TODO 加载中状态           
            let params = {
                bUserUid: this.businessUserUid
            }
            let dataResponse
            try{
                dataResponse = await HTTP('app/buser/getSkillByBuserUid', params)
                if(dataResponse.code !== 200){
                    this.$toast(dataResponse.msg || '异常')
                    return
                }
                console.log('--技能标签--')
                console.log(dataResponse.data)
                this.orightSkill = dataResponse.data
                this.demandList = dataResponse.data.filter(e => e.flag).map(e => e.name)
                // 初始化需求效果
                this.demandDone()
                // this.demandList = dataResponse.data
            }catch(e){
                console.log(e)
                this.$toast('数据开小差了')
            }
        },
        ...mapMutations([
            'UPDATE',
        ]),
        goAddAddress(){
            this.$router.push('/performance/address')
        },
        success,
        upDoordateCelectOnChange(picker, value, index){
            // console.log(value)
            this.upDoordateCelect = value.text
            this.UPDATE(['payOrderUpDoordateCelectIndex', index])
        },
        updoorDateDone(){
            let okList = this.dateCelectColumns.filter(e => !e.disabled).map(e => e.text)
            // console.log(okList)
            if(this.payOrderUpDoordateCelectIndex === 0 && okList.length > 0){
                this.upDoordateCelect = okList[0] //this.dateCelectColumns[0].text
            }
            this.UPDATE(['payOrderUpDoorDateCelectActive', this.upDoordateCelect])
            this.openUpdoorDate = false
        },
        demandChange(picker, value, index){
            console.log('---picker---')
            console.log(picker, value)
            this.demandCelect = value
            this.UPDATE(['payOrderDemandIndex', index])
        },
        demandDone(){
                console.log(this.dateCelectColumns)
            if(this.payOrderDemandIndex === 0){
                this.demandCelect = this.demandList[0]
            }
            if(!this.demandCelect){
                console.log('this.demandCelect null')
                return
            }
            this.UPDATE(['payOrderDemandActive', this.demandCelect])            
            this.UPDATE(['payOrderDemandUid', this.orightSkill.find(e => e.name === this.demandCelect).uid])
            this.openDemand = false
        },
        onFilterTime(selected){
            this.isOpTimes = false
            // console.log('time selected')
            // console.log(selected)
            this.UPDATE(['payOrderConventionDate', selected])
            // 修改日期后再检测
            // this.dateCelectColumns = dafaultDateCelectColumns(this.updoorDateList, selected)
            this.getupdoorDate((list) => {
                // console.log('---获取的上门时间---')
                // console.log(list)
                // 设置上门时间列表
                this.dateCelectColumns = dafaultDateCelectColumns(list, selected)
                this.updoorDateList = list.map(e => e)
                // 初始化选择
                this.upDoordateCelect = ''
                this.UPDATE(['payOrderUpDoorDateCelectActive', ''])
            }) 
        },
        calendarClose(){
            this.isOpTimes = false
        },
        switchPayWay(index){
            this.UPDATE(['payOrderPayWayActiveIndex', index])
            this.isPayWay = false
        },
        addBank(){
            this.$router.push('/performance/bindbank?type=3&userUid=' + getuserUid())
        }
    }
}
</script>
<style lang="scss" scoped>
@import './style.scss';
</style>
